package net.thxjj.adminServer.mongodao;

import net.thxjj.adminServer.entity.StaticBean;
import net.thxjj.adminServer.entity.aep.ProfileLog;
import net.thxjj.adminServer.util.DataUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MongoProfileDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    //导入所有数据
    public void saveAllData(List<ProfileLog> list){
        mongoTemplate.insert(list,ProfileLog.class);
    }

    //导入校验（如果有timestamp和deviceId重合则更新）
    public void saveProfileDatas(List<ProfileLog> list){
        for (ProfileLog profile:
                list) {
           ProfileLog po = findProfileLogByDeviceIdAndTime(profile.getDeviceId(),profile.getTimestamp());
           if(po==null){
               mongoTemplate.save(profile);
           }else{
               updateProfileLog(profile);
           }
        }
    }

    public void saveProfileLog(ProfileLog profileLog){
        ProfileLog po = findProfileLogByDeviceIdAndTime(profileLog.getDeviceId(),profileLog.getTimestamp());
        if(po==null){
            mongoTemplate.save(profileLog);
        }else{
            updateProfileLog(profileLog);
        }
    }

    private void updateProfileLog(ProfileLog profileLog) {

        Query query = new Query(Criteria.where("deviceId").is(profileLog.getDeviceId()).and("timestamp").is(profileLog.getTimestamp()));
        Update update = new Update()
                .set("TData",profileLog.getTData())
                .set("SNR",profileLog.getSNR())
                .set("RSRP",profileLog.getRSRP())
                .set("IMEI",profileLog.getTData())
                .set("Cell_ID_Length",profileLog.getCell_ID_Length())
                .set("Cell_ID",profileLog.getCell_ID())
                .set("CSQ",profileLog.getCSQ())
                .set("Battery_Level",profileLog.getBattery_Level())
                .set("Alarm_Status",profileLog.getAlarm_Status())
                .set("alarmLevel",profileLog.getAlarmLevel());
        mongoTemplate.upsert(query,update,ProfileLog.class);
    }

    private ProfileLog findProfileLogByDeviceIdAndTime(String deviceId,long time){
        Query query = new Query(Criteria.where("deviceId").is(deviceId).and("timestamp").is(time));
        return mongoTemplate.findOne(query,ProfileLog.class);
    }

    public ProfileLog getSmokeStatus(String deviceId){
        Query query = new Query(Criteria.where("deviceId").is(deviceId));
        query.with(new Sort(Sort.Direction.DESC,"timestamp"));
        return mongoTemplate.findOne(query,ProfileLog.class);
    }


    public List<ProfileLog> getAlllogs(String deviceId){
        Query query = new Query(Criteria.where("deviceId").is(deviceId));
        query.with(new Sort(Sort.Direction.DESC,"timestamp"));
        return mongoTemplate.find(query,ProfileLog.class);
    }

    public List<ProfileLog> getProfileLogsByTime(String deviceId,long start_time,long end_time){
        Query query = new Query(Criteria.where("deviceId").is(deviceId).andOperator(Criteria.where("timestamp").gt(start_time),Criteria.where("timestamp").lt(end_time)));
        query.with(new Sort(Sort.Direction.DESC,"timestamp"));
        return mongoTemplate.find(query,ProfileLog.class);
    }

    public StaticBean getSmokeValueStatic(String device_id,long start_time,long end_time){
        Aggregation aggregation=Aggregation.newAggregation(
                Aggregation.match(Criteria.where("deviceId").is(device_id).andOperator(Criteria.where("timestamp").gt(start_time),Criteria.where("timestamp").lt(end_time))),
                Aggregation.group().max("alarmLevel").as("max").min("alarmLevel").as("min").avg("alarmLevel").as("avg"));

        StaticBean staticBean =  mongoTemplate.aggregate(aggregation,"th_profile_log", StaticBean.class).getUniqueMappedResult();
        //平均值保留两位小数
        String dea = DataUtils.getDoubleString(staticBean.getAvg());
        staticBean.setAvg(dea);
        return staticBean;
    }

    public StaticBean getBatteryValueStatic(String device_id,long start_time,long end_time){
        Aggregation aggregation=Aggregation.newAggregation(
                Aggregation.match(Criteria.where("deviceId").is(device_id).andOperator(Criteria.where("timestamp").gt(start_time),Criteria.where("timestamp").lt(end_time))),
                Aggregation.group().max("Battery_Level").as("max").min("Battery_Level").as("min").avg("Battery_Level").as("avg"));

        StaticBean staticBean =  mongoTemplate.aggregate(aggregation,"th_profile_log", StaticBean.class).getUniqueMappedResult();
        //平均值保留两位小数
        String dea = DataUtils.getDoubleString(staticBean.getAvg());
        staticBean.setAvg(dea);
        return staticBean;
    }

    public StaticBean getSnrStatic(String device_id,long start_time,long end_time){
        Aggregation aggregation=Aggregation.newAggregation(
                Aggregation.match(Criteria.where("deviceId").is(device_id).andOperator(Criteria.where("timestamp").gt(start_time),Criteria.where("timestamp").lt(end_time))),
                Aggregation.group().max("SNR").as("max").min("SNR").as("min").avg("SNR").as("avg"));

        StaticBean staticBean =  mongoTemplate.aggregate(aggregation,"th_profile_log", StaticBean.class).getUniqueMappedResult();
        //平均值保留两位小数
        String dea = DataUtils.getDoubleString(staticBean.getAvg());
        staticBean.setAvg(dea);
        return staticBean;
    }

    public StaticBean getRsrpStatic(String device_id,long start_time,long end_time){
        Aggregation aggregation=Aggregation.newAggregation(
                Aggregation.match(Criteria.where("deviceId").is(device_id).andOperator(Criteria.where("timestamp").gt(start_time),Criteria.where("timestamp").lt(end_time))),
                Aggregation.group().max("RSRP").as("max").min("RSRP").as("min").avg("RSRP").as("avg"));

        StaticBean staticBean =  mongoTemplate.aggregate(aggregation,"th_profile_log", StaticBean.class).getUniqueMappedResult();
        //平均值保留两位小数
        String dea = DataUtils.getDoubleString(staticBean.getAvg());
        staticBean.setAvg(dea);
        return staticBean;
    }

    public StaticBean getTempStatic(String device_id,long start_time,long end_time){
        Aggregation aggregation=Aggregation.newAggregation(
                Aggregation.match(Criteria.where("deviceId").is(device_id).andOperator(Criteria.where("timestamp").gt(start_time),Criteria.where("timestamp").lt(end_time))),
                Aggregation.group().max("TData").as("max").min("TData").as("min").avg("TData").as("avg"));

        StaticBean staticBean =  mongoTemplate.aggregate(aggregation,"th_profile_log", StaticBean.class).getUniqueMappedResult();
        //平均值保留两位小数
        String dea = DataUtils.getDoubleString(staticBean.getAvg());
        staticBean.setAvg(dea);
        return staticBean;
    }

    public StaticBean getCsqStatic(String device_id,long start_time,long end_time){
        Aggregation aggregation=Aggregation.newAggregation(
                Aggregation.match(Criteria.where("deviceId").is(device_id).andOperator(Criteria.where("timestamp").gt(start_time),Criteria.where("timestamp").lt(end_time))),
                Aggregation.group().max("CSQ").as("max").min("CSQ").as("min").avg("CSQ").as("avg"));

        StaticBean staticBean =  mongoTemplate.aggregate(aggregation,"th_profile_log", StaticBean.class).getUniqueMappedResult();
        //平均值保留两位小数
        String dea = DataUtils.getDoubleString(staticBean.getAvg());
        staticBean.setAvg(dea);
        return staticBean;
    }


}
